package utils

import (
	"LoginTemplate/models"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/golang-jwt/jwt/v5"
	"time"
)

type MyClaims struct {
	UserInfo models.Staff
	jwt.RegisteredClaims
}

func MakeToken(userInfo models.Staff) (string, error) {
	jwt_key := []byte(beego.AppConfig.String("jwt_key"))
	token_hour, _ := beego.AppConfig.Int64("token_hour")
	hour_duration, _ := time.ParseDuration(fmt.Sprintf("%dh", token_hour))
	// Create claims with multiple fields populated
	claims := MyClaims{
		userInfo,
		jwt.RegisteredClaims{
			// A usual scenario is to set the expiration time relative to the current time
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(hour_duration)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()),
			Issuer:    "zhxj",
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString(jwt_key)
	return tokenString, err
}

func VerifyToken(tokenString string) (models.Staff, error) {
	var userInfo models.Staff
	jwt_key := beego.AppConfig.String("jwt_key")
	token, err := jwt.ParseWithClaims(tokenString, &MyClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(jwt_key), nil
	}, jwt.WithLeeway(5*time.Second))

	if claims, ok := token.Claims.(*MyClaims); ok && token.Valid {
		userInfo = claims.UserInfo
		return userInfo, nil
	} else {
		return userInfo, err
	}
}
